#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
缓存管理模块
负责教室查询数据的缓存和过期管理
"""

import time
from typing import Dict, List, Any, Optional, Tuple


class CacheManager:
    """缓存管理器"""

    def __init__(self, cache_ttl: int = 600):
        """
        初始化缓存管理器

        Args:
            cache_ttl: 缓存过期时间（秒），默认10分钟
        """
        self.cache_ttl = cache_ttl
        self._cache: Dict[str, Dict[str, Any]] = {}

    def generate_cache_key(self, building_code: str, week: str) -> str:
        """生成缓存键 - 使用教学楼+周次作为缓存键"""
        return f"{building_code}_{week}"

    def generate_old_cache_key(self, building_code: str, date_str: str, sections: str) -> str:
        """生成旧的缓存键格式，用于兼容性"""
        return f"{building_code}_{date_str}_{sections}"

    def is_cache_expired(self, cached_data: Dict[str, Any], current_time: float) -> bool:
        """检查缓存是否过期"""
        return current_time - cached_data["timestamp"] >= self.cache_ttl

    def clean_expired_cache(self, current_time: Optional[float] = None) -> int:
        """
        清理过期的缓存项

        Args:
            current_time: 当前时间戳，如果为None则使用当前时间

        Returns:
            清理的缓存项数量
        """
        if current_time is None:
            current_time = time.time()

        expired_keys = []
        for cache_key, cached_data in self._cache.items():
            if self.is_cache_expired(cached_data, current_time):
                expired_keys.append(cache_key)

        # 删除过期的缓存
        for key in expired_keys:
            del self._cache[key]

        if expired_keys:
            print(f"[DEBUG] 清理了 {len(expired_keys)} 个过期缓存项")

        return len(expired_keys)

    def get(self, cache_key: str) -> Optional[Dict[str, Any]]:
        """获取缓存数据"""
        if cache_key not in self._cache:
            return None

        current_time = time.time()
        cached_data = self._cache[cache_key]

        if self.is_cache_expired(cached_data, current_time):
            print(f"[DEBUG] ⏰ 缓存已过期（{current_time - cached_data['timestamp']:.1f}秒）")
            del self._cache[cache_key]
            return None

        return cached_data

    def set(self, cache_key: str, rooms_info: List[Dict[str, Any]], all_rooms: List[str], building_code: str) -> None:
        """设置缓存数据"""
        current_time = time.time()
        self._cache[cache_key] = {
            "rooms_info": rooms_info,  # 存储原始的教室详细信息
            "all_rooms": all_rooms,
            "building_code": building_code,
            "timestamp": current_time
        }
        print(f"[DEBUG] 缓存已保存: {cache_key}, 教室数量: {len(all_rooms)}, 详细信息: {len(rooms_info)}条")

    def get_cache_info(self) -> Dict[str, Any]:
        """获取缓存信息（用于调试）"""
        current_time = time.time()
        cache_info = {
            "total_cache_items": len(self._cache),
            "valid_cache_items": 0,
            "expired_cache_items": 0,
            "cache_details": []
        }

        for cache_key, cached_data in self._cache.items():
            age_seconds = current_time - cached_data["timestamp"]
            is_expired = self.is_cache_expired(cached_data, current_time)

            if is_expired:
                cache_info["expired_cache_items"] += 1
            else:
                cache_info["valid_cache_items"] += 1

            cache_info["cache_details"].append({
                "cache_key": cache_key,
                "building_code": cached_data.get("building_code", "unknown"),
                "age_seconds": age_seconds,
                "age_minutes": age_seconds / 60,
                "is_expired": is_expired,
                "rooms_count": len(cached_data.get("all_rooms", []))
            })

        return cache_info

    def should_clean_cache(self) -> bool:
        """判断是否需要清理缓存（每10次查询清理一次）"""
        return hash(str(time.time())) % 10 == 0

    def clear_all(self) -> None:
        """清空所有缓存"""
        self._cache.clear()
        print("[DEBUG] 所有缓存已清空")